<template>
  <div class="main">
    <search ref="mysearch" @doReset="doReset" @doQuery="doRefresh" :ruleform="ruleForm">
      <template slot="top">
        <el-form-item label="系统名称:" prop="systemId" size="small" label-width="80px">
          <el-select v-model="ruleForm.systemId" placeholder="请输入系统名称">
            <el-option value="" label="全部"></el-option>
            <el-option v-for="(item, index)  in systemNameOption" :label="item.name" :value="item.id"
              :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务名称:" prop="serviceId" size="small" label-width="95px">
          <el-select v-model="ruleForm.serviceId" placeholder="请输入服务名称">
            <el-option value="" label="全部"></el-option>
            <el-option v-for="(item, index)  in serverNameOption" :label="item.name" :value="item.id"
              :key="index"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="报警手机号" prop="alarmCellPhone" size="small" label-width="95px">
          <el-select v-model="ruleForm.alarmCellPhone" placeholder="请选择">
            <el-option value="" label="全部"></el-option>
            <el-option v-for="(item, index) in alarmCellPhoneOption" :label="item.cellPhone" :value="item.id"
              :key="index"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="创建时间:" prop="createDate" size="small" class="datePicker" label-width="95px">
          <el-date-picker v-model="ruleForm.createDate" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
      </template>
    </search>

    <div class="table-warpper">
      <mytable ref="mytable" :config="tableconfig">
        <!-- 新增 -->
        <div slot="mytablebody">
          <el-button type="primary" size="small" @click="handleAdd('add')" style="margin-bottom:24px">添加</el-button>
        </div>
        <!-- 是否启用 -->
        <template v-slot:enable="{ data }">
          <p v-if="data.enable == 1">是</p>
          <p v-else>否</p>
        </template>
         <!-- 正则表达式 -->
         <template v-slot:responseSuccessRegularExpression="{ data }">
          <p v-if="data.responseSuccessRegularExpression == ''">-</p>
          <p v-else>{{ data.responseSuccessRegularExpression }}</p>
        </template>
        <!-- 操作 -->
        <template v-slot:operation="{ data }">
          <el-button type="text" @click="detail(data)">查看</el-button>
          <el-button type="text" @click="handleAdd('edit', data)">编辑</el-button>
          <el-button type="text" @click="del(data)">删除</el-button>
          <el-button type="text" @click="execute(data)">执行</el-button>
        </template>
        <!-- 操作 -->
      </mytable>
    </div>
    <!-- 新增、编辑 -->
    <el-dialog :title="key == 'add' ? '添加任务' : '编辑任务'" :visible.sync="dialogVisibleAdd" width="30%"
      :before-close="handleClose" class="dialog">

      <el-form :model="addForm" ref="addForm" :rules="addRules" label-suffix=":" label-position="left">
        <el-form-item label="接口名称" prop="apiId" :label-width="formLabelWidth">
          <el-select v-model="addForm.apiId" placeholder="请输入接口名称" style="width:100%;" size="small">
            <el-option v-for="(item, index) in joggleNameOption" :label="item.name" :value="item.id"
              :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="调度表达式" prop="scheduleExpression" :label-width="formLabelWidth">
          <el-input v-model="addForm.scheduleExpression" placeholder="请输入调用表达式" size="small"></el-input>
        </el-form-item>
        <!-- <el-form-item label="任务处理器" prop="jobHandler" :label-width="formLabelWidth">
                    <el-input v-model="addForm.jobHandler" placeholder="请输入名称"></el-input>
                </el-form-item> -->
        <el-form-item label="是否启用" prop="enable" :label-width="formLabelWidth" class="enable">
          <el-select v-model="addForm.enable" style="width:100%" size="small">
            <el-option label="是" :value="1"></el-option>
            <el-option label="否" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报警邮箱" prop="alarmEmailId" :label-width="formLabelWidth">
          <el-select v-model="addForm.alarmEmailId" placeholder="请输入报警邮箱" style="width:100%;" size="small">
            <el-option v-for="(item, index) in alarmEmailOption" :label="item.email" :value="item.id"
              :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报警手机号" prop="alarmCellPhoneId" :label-width="formLabelWidth">
          <el-select v-model="addForm.alarmCellPhoneId" placeholder="请输入报警手机号" style="width:100%;" size="small">
            <el-option v-for="(item, index) in alarmCellPhoneOption" :label="item.cellPhone" :value="item.id"
              :key="index"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center;">
        <el-button type="primary" @click="getAdd('addForm', key)" size="small">确 认</el-button>
        <el-button @click="handleClose" size="small">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 任务详情 -->
    <drawer ref="drawer" :data="selectItem" title="任务详情" :columns="columns"></drawer>
    <!-- 删除 -->
    <!-- <el-dialog title="删除" :visible.sync="dialogVisibleDel" width="30%">
      <div class="content">您是否删除数据？</div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleDel = false">取 消</el-button>
        <el-button type="primary" @click="handleDelConfrim">确 定</el-button>
      </div>
    </el-dialog> -->
  </div>
</template>

<script>
import mytable from "@/components/table.vue";
// import AddTask from "../components/AddTask.vue";
import drawer from "./components/drawer.vue";
import search from "./components/search.vue";
// import DialogMessage from "@/components/DialogMessage.vue";
import { interFaceColumns, interFaceTableconfig } from "../data/configData.js";
import { phoneList, emailList, joggleList, joggleAdd, joggleEdit, joggleDetail, joggleExecute, joggleDel, systemFind, serviceData, apiData } from "@/api/controlSystem/joggle.js"
import { changeParam } from "@/utils/helper";
export default {
  components: {
    mytable,
    // AddTask,
    drawer,
    search,
    // DialogMessage,
  },
  data() {
    return {
      ruleForm: {
        startTime: "",
        endTime: "",
        createDate: [],
        systemId: null,
        serviceId: null,
        isMain:false,
        pageNo: 1,
        pageSize: 20,
      },
      formLabelWidth: '120px',
      systemNameOption: [],
      serverNameOption: [],
      alarmCellPhoneOption: [],
      alarmEmailOption: [],
      joggleNameOption: [],
      // dialogVisibleDel: false,
      dialogVisibleAdd: false,
      addForm: {
        apiId: null,
        scheduleExpression: "",
        // jobHandler: "",
        enable: null,
        alarmEmailId: null,
        alarmCellPhoneId: null
      },
      addRules: {
        apiId: [{ required: true, message: '请选择接口名称', trigger: 'change' }],
        scheduleExpression: [{ required: true, message: '请输入调用表达式', trigger: 'blur' }],
        // jobHandler: [{ required: true, message: '请输入任务处理器', trigger: 'blur' }],
        alarmEmailId: [{ required: true, message: '请输入邮箱地址', trigger: 'change' }],
        alarmCellPhoneId: [{ required: true, message: '请输入手机号', trigger: 'change' }],
      },
      columns: interFaceColumns,
      selectItem: "",
      key: "",
      delId: "",
      tableconfig: interFaceTableconfig,
    };
  },
  mounted() {
    this.handleList();
    this.handlePhone();
    this.handleEmail();
    this.handleName();
  },
  methods: {
    // 名称
    handleName() {
      let params = {
        name: '',
        pageNo: 1,
        pageSize: 99999,
      }
      systemFind(changeParam({ ...params })).then(res => {
        console.log('tag', res)
        if (res.success) {
          this.systemNameOption = res.result.list
        }
      })
      let envParams = {
        systemId: '',
        systemName: '',
        serviceId: '',
        name: '',
        pageNo: 1,
        pageSize: 99999,
      }
      serviceData(changeParam({ ...envParams })).then(res => {
        console.log(res, 'rrrrrrr');
        if (res.success) {
          this.serverNameOption = res.result.list;
        }
      })
      let apiParams = {
        id: "",
        name: "",
        systemId: "",
        systemName: "",
        environmentId: "",
        environmentName: "",
        serviceId: "",
        serviceName: "",
        pageNo: 1,
        pageSize: 9999,
      }
      apiData(changeParam({ ...apiParams })).then(res => {
        if (res.success) {
          this.joggleNameOption = res.result.list;
        }
      })
    },
    // 报警手机号
    handlePhone() {
      phoneList().then(res => {
        if (res.success) {
          this.alarmCellPhoneOption = res.result;
        }
      })
    },
    // 报警邮箱
    handleEmail() {
      emailList().then(res => {
        if (res.success) {
          this.alarmEmailOption = res.result;
        }
      })
    },
    // 重置
    doReset() {
      console.log(Object.keys(this.ruleForm), "this.ruleForm");
      Object.keys(this.ruleForm).slice(0, -2).map(item => {
        this.ruleForm[item] = "";
      });
      // this.$message({
      //   message: "已重置",
      //   type: "success",
      // });
      this.doRefresh();
    },
    // 搜索
    doRefresh() {
      this.tableconfig.currentpage = 1;
      this.ruleForm.pageNo = 1;
      this.$refs.mytable.$emit("handleGoTop");
      this.ruleForm.isMain = false;
      this.handleList();
    },
    // 页码数更新
    handleSizeChange(val) {
      console.log('tag', val)
      this.ruleForm.pageNo = 1;
      this.ruleForm.pageSize = val;
      this.ruleForm.isMain = false;
      this.handleList();
      //表格回到顶部
      this.$refs.mytable.$emit('handleGoTop');
    },
    // 当前页码更新
    handleCurrentChange(val) {
      console.log('val', val)
      this.ruleForm.pageNo = val;
      console.log(this.ruleForm.pageNo, 'this.tableconfig.currentpage');
      this.ruleForm.isMain = false;
      this.handleList();
      //表格回到顶部
      this.$refs.mytable.$emit('handleGoTop');
    },
    // 表格列表
    async handleList() {
      this.tableconfig.loading = true;
      this.tableconfig.currentpage = this.ruleForm.pageNo;
      this.tableconfig.pagesize = this.ruleForm.pageSize;
      this.ruleForm.startTime = this.ruleForm.createDate[0];
      this.ruleForm.endTime = this.ruleForm.createDate[1];
      let joggleResult = await joggleList(this.ruleForm)
      if (joggleResult.success) {
        this.tableconfig.tabledata = joggleResult.result.list;
        this.tableconfig.total = joggleResult.result.total;
        this.ruleForm.pageNo = joggleResult.result.pageNum;
        this.ruleForm.pageSize = joggleResult.result.pageSize;
      }
      this.tableconfig.loading = false
    },
    //新增编辑
    handleAdd(index, data) {
      console.log('tag', index, data)
      this.key = index;
      if (this.key == 'edit') {
        this.ruleForm.isMain = true
        joggleDetail(data.id,this.ruleForm.isMain).then(res => {
          console.log('res', res)
          if (res.success) {
            this.addForm = res.result
          }
        })
      }
      this.dialogVisibleAdd = true;
    },
    // 关闭弹窗
    handleClose() {
      this.dialogVisibleAdd = false;
      this.$refs.addForm.resetFields();
    },
    //新增编辑
    getAdd(fromName, key) {
      this.$refs[fromName].validate(valid => {
        if (valid) {
          if (key == 'add') {
            joggleAdd(this.addForm).then(res => {
              console.log('tag11111111', res)
              if (res.success) {
                if (res.result) {
                  this.$message.success(res.message);
                  this.dialogVisibleAdd = false;
                  this.$refs.addForm.resetFields();
                  this.ruleForm.isMain = true;
                  this.handleList()
                } else {
                  this.$message.error(res.message)
                  return false;
                }
              } else {
                this.$message.error(res.message)
              }
            })
          } else {
            joggleEdit(this.addForm).then(res => {
              if (res.success) {
                if (res.result) {
                  this.$message.success(res.message);
                  this.dialogVisibleAdd = false;
                  this.ruleForm.isMain = true;
                  this.handleList()
                } else {
                  this.$message.error(res.message)
                  return false;
                }
              } else {
                this.$message.error(res.message)
              }
            })
          }
        }
      })
    },
    detail(data) {
      this.selectItem = data;
      console.log('tag', data)
      if (this.selectItem.enable == 1) {
        this.selectItem.enable = "是"
      } else {
        this.selectItem.enable = "否"
      }
      this.$refs.drawer.open(this.selectItem);
    },
    // 删除
    del(data) {
      // this.dialogVisibleDel = true;
      this.delId = data.id;
      this.$confirm('确认删除该条记录?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await this.handleDelConfrim()
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.doRefresh()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 确定删除
    handleDelConfrim() {
      // if (type == 1) {
      //   this.tableconfig.tabledata = this.tableconfig.tabledata.filter(
      //     (item) => item.id != this.selectItem.id
      //   );
      // }
      joggleDel(this.delId).then(res => {
        console.log('tag', res)
        if (res.success) {
          if (res.result) {
            this.$message.success(res.message);
            this.dialogVisibleDel = false;
            this.handleList()
          } else {
            this.$message.error(res.message);
            return false;
          }
        } else {
          this.$message.error(res.message);
        }
      })
    },
    // 执行任务
    execute(data) {
      joggleExecute(data.id).then(res => {
        if (res.success) {
          this.$message.success('此任务执行成功')
        } else {
          this.$message.error('此任务执行失败')
        }
      })
    },
  },
  created() {
    this.tableconfig.tabledata = [
      // {
      //   // id: 1,
      //   sysName: "windows10",
      //   envName: "测试环境",
      //   serviceName: "订单服务",
      //   interFaceName: "/api/add",
      //   enable: "是",
      //   taskProcessor: "任务处理器",
      //   expression: "调度表达式",
      //   email: "123@163.com",
      //   tel: "13333333333",
      //   // ip: "127.0.0.1",
      //   // port: "8080",
      //   // userName: "admin",
      //   // password: "123456",
      //   regularExpression: "test",
      //   createTime: "2023-03-08 16:24:30",
      // },
      // {
      //   id: 2,
      //   sysName: "windows10",
      //   envName: "测试环境",
      //   serviceName: "订单服务",
      //   interFaceName: "/api/add",
      //   isUse: "是",
      //   taskProcessor: "任务处理器",
      //   expression: "调度表达式",
      //   email: "123@163.com",
      //   tel: "13333333333",
      //   ip: "127.0.0.1",
      //   port: "8080",
      //   userName: "admin",
      //   password: "123456",
      //   regularExpression: "test",
      //   createTime: "2023-03-08 16:24:30",
      // },
      // {
      //   id: 3,
      //   sysName: "windows10",
      //   envName: "测试环境",
      //   serviceName: "订单服务",
      //   interFaceName: "/api/add",
      //   isUse: "是",
      //   taskProcessor: "任务处理器",
      //   expression: "调度表达式",
      //   email: "123@163.com",
      //   tel: "13333333333",
      //   ip: "127.0.0.1",
      //   port: "8080",
      //   userName: "admin",
      //   password: "123456",
      //   regularExpression: "test",
      //   createTime: "2023-03-08 16:24:30",
      // },
    ];
  },
};
</script>
<style lang="scss" scoped>
.main {
  .datePicker ::v-deep .el-range-separator {
    width: 30px;
  }

  .dialog-footer {
    text-align: center;
  }

  .content {
    font-size: 18px;
    font-weight: 600;
    text-align: center;

  }
  .el-button--primary{
    background-color: #3C77FF;
    border-color: #3C77FF;
  }
  .el-button--text{
    color: #3C77FF;
    font-weight: 400;
  }

  .enable {
    ::v-deep .el-form-item__label {
      width: 104px !important;
      margin-left: 11px;
    }
  }

  .dialog {
    ::v-deep .el-dialog__header {
      padding: 20px 0px 10px;
      border-bottom: 1px solid #DDDDDD;
      margin: 0 20px;
      font-size: 16px;
      font-weight: 600;
      color: #333333;
      line-height: 24px;
    }
    ::v-deep .el-dialog__body {
            // padding-top: 15px;
            padding: 15px 90px;
            color: #606266;
            font-size: 14px;
            .el-form-item{
                margin-bottom: 15px;
            }
        
        }
  }
}
</style>
